#include "list.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 初始化用户链表
UserList* initUserList() 
{
    UserList *list = (UserList*)malloc(sizeof(UserList));
    if (list) {
        list->head = NULL;
        list->count = 0;
    }
    return list;
}

// 从JSON解析订单数据
UserOrder* parseOrders(cJSON *ordersArray, int *orderCount) 
{
    if (!ordersArray || !cJSON_IsArray(ordersArray)) {
        *orderCount = 0;
        return NULL;
    }
    
    int count = cJSON_GetArraySize(ordersArray);
    if (count == 0) {
        *orderCount = 0;
        return NULL;
    }
    
    UserOrder *orders = (UserOrder*)malloc(count * sizeof(UserOrder));
    if (!orders) {
        *orderCount = 0;
        return NULL;
    }
    
    for (int i = 0; i < count; i++) {
        cJSON *orderItem = cJSON_GetArrayItem(ordersArray, i);
        if (orderItem) {
            cJSON *item = cJSON_GetObjectItem(orderItem, "TrainNumber");
            if (item) strncpy(orders[i].TrainNumber, item->valuestring, sizeof(orders[i].TrainNumber));
            
            item = cJSON_GetObjectItem(orderItem, "start");
            if (item) strncpy(orders[i].start, item->valuestring, sizeof(orders[i].start));
            
            item = cJSON_GetObjectItem(orderItem, "end");
            if (item) strncpy(orders[i].end, item->valuestring, sizeof(orders[i].end));
            
            item = cJSON_GetObjectItem(orderItem, "DepartTime");
            if (item) strncpy(orders[i].DepartTime, item->valuestring, sizeof(orders[i].DepartTime));
            
            item = cJSON_GetObjectItem(orderItem, "date");
            if (item) strncpy(orders[i].date, item->valuestring, sizeof(orders[i].date));
            
            item = cJSON_GetObjectItem(orderItem, "ArriveTime");
            if (item) strncpy(orders[i].ArriveTime, item->valuestring, sizeof(orders[i].ArriveTime));
            
            item = cJSON_GetObjectItem(orderItem, "TimeDifference");
            if (item) strncpy(orders[i].TimeDifference, item->valuestring, sizeof(orders[i].TimeDifference));
            
            item = cJSON_GetObjectItem(orderItem, "seatNumber");
            if (item) orders[i].seatNumber = item->valueint;
        }
    }
    
    *orderCount = count;
    return orders;
}

// 从JSON文件加载用户数据到链表
int loadUsersFromFile(UserList *list, const char *filename) 
{
    if (!list) return 0;
    
    FILE *file = fopen(filename, "r");
    if (!file) {
        printf("无法打开文件: %s\n", filename);
        return 0;
    }
    
    fseek(file, 0, SEEK_END);
    long length = ftell(file);
    fseek(file, 0, SEEK_SET);
    
    char *data = (char*)malloc(length + 1);
    if (!data) {
        fclose(file);
        return 0;
    }
    
    fread(data, 1, length, file);
    data[length] = '\0';
    fclose(file);
    
    cJSON *root = cJSON_Parse(data);
    free(data);
    
    if (!root) {
        printf("JSON解析失败\n");
        return 0;
    }
    
    cJSON *codeItem = cJSON_GetObjectItem(root, "code");
    if (!codeItem || codeItem->valueint != 200) {
        cJSON_Delete(root);
        return 0;
    }
    
    cJSON *dataArray = cJSON_GetObjectItem(root, "data");
    if (!dataArray || !cJSON_IsArray(dataArray)) {
        cJSON_Delete(root);
        return 0;
    }
    
    int userCount = cJSON_GetArraySize(dataArray);
    for (int i = 0; i < userCount; i++) {
        cJSON *userItem = cJSON_GetArrayItem(dataArray, i);
        if (!userItem) continue;
        
        User *user = (User*)malloc(sizeof(User));
        if (!user) continue;
        
        // 解析用户基本信息
        cJSON *item = cJSON_GetObjectItem(userItem, "username");
        if (item) strncpy(user->username, item->valuestring, sizeof(user->username));
        
        item = cJSON_GetObjectItem(userItem, "userPassword");
        if (item) strncpy(user->userPassword, item->valuestring, sizeof(user->userPassword));
        
        item = cJSON_GetObjectItem(userItem, "state");
        if (item) strncpy(user->state, item->valuestring, sizeof(user->state));
        
        // 解析订单信息
        cJSON *ordersArray = cJSON_GetObjectItem(userItem, "userorder");
        user->orders = parseOrders(ordersArray, &user->orderCount);
        
        user->next = NULL;
        
        // 添加到链表
        addUser(list, user);
    }
    
    cJSON_Delete(root);
    return 1;
}

// 将订单数据转换为JSON
cJSON* ordersToJSON(UserOrder *orders, int orderCount) {
    cJSON *ordersArray = cJSON_CreateArray();
    if (!ordersArray) return NULL;
    
    for (int i = 0; i < orderCount; i++) {
        cJSON *orderObj = cJSON_CreateObject();
        if (!orderObj) continue;
        
        cJSON_AddStringToObject(orderObj, "TrainNumber", orders[i].TrainNumber);
        cJSON_AddStringToObject(orderObj, "start", orders[i].start);
        cJSON_AddStringToObject(orderObj, "end", orders[i].end);
        cJSON_AddStringToObject(orderObj, "DepartTime", orders[i].DepartTime);
        cJSON_AddStringToObject(orderObj, "date", orders[i].date);
        cJSON_AddStringToObject(orderObj, "ArriveTime", orders[i].ArriveTime);
        cJSON_AddStringToObject(orderObj, "TimeDifference", orders[i].TimeDifference);
        cJSON_AddNumberToObject(orderObj, "seatNumber", orders[i].seatNumber);
        
        cJSON_AddItemToArray(ordersArray, orderObj);
    }
    
    return ordersArray;
}

// 保存链表数据到JSON文件
int saveUsersToFile(UserList *list, const char *filename) 
{
    if (!list) return 0;
    
    cJSON *root = cJSON_CreateObject();
    if (!root) return 0;
    
    cJSON_AddNumberToObject(root, "code", 200);
    cJSON_AddStringToObject(root, "checkCode", "userManagement");
    
    cJSON *dataArray = cJSON_CreateArray();
    if (!dataArray) 
    {
        cJSON_Delete(root);
        return 0;
    }
    
    User *current = list->head;
    while (current) 
    {
        cJSON *userObj = cJSON_CreateObject();
        if (!userObj) continue;
        
        cJSON_AddStringToObject(userObj, "username", current->username);
        cJSON_AddStringToObject(userObj, "userPassword", current->userPassword);
        cJSON_AddStringToObject(userObj, "state", current->state);
        
        cJSON *ordersArray = ordersToJSON(current->orders, current->orderCount);
        if (ordersArray) {
            cJSON_AddItemToObject(userObj, "userorder", ordersArray);
        }
        
        cJSON_AddItemToArray(dataArray, userObj);
        current = current->next;
    }
    
    cJSON_AddItemToObject(root, "data", dataArray);
    
    char *jsonStr = cJSON_Print(root);
    cJSON_Delete(root);
    
    if (!jsonStr) return 0;
    
    FILE *file = fopen(filename, "w");
    if (!file) {
        free(jsonStr);
        return 0;
    }
    
    fputs(jsonStr, file);
    fclose(file);
    free(jsonStr);

    return 1;
}

// 添加用户到链表
void addUser(UserList *list, User *user) 
{
    if (!list || !user) return;
    
    if (list->head == NULL) {
        list->head = user;
    } else {
        User *current = list->head;
        while (current->next) {
            current = current->next;
        }
        current->next = user;
    }
    user->next = NULL;
    list->count++;
}

// 根据用户名查找用户
User* findUser(UserList *list, const char *username) 
{
    if (!list || !username) return NULL;
    
    User *current = list->head;
    while (current) {
        if (strcmp(current->username, username) == 0) {
            return current;
        }
        current = current->next;
    }
    
    return NULL;
}



// 释放链表内存
void freeUserList(UserList *list) 
{
    if (!list) return;
    
    User *current = list->head;
    while (current) {
        User *next = current->next;
        if (current->orders) {
            free(current->orders);
        }
        free(current);
        current = next;
    }
    
    // free(list);
}


